package com.ybwh.springboot2.util;

import org.springframework.util.PropertyPlaceholderHelper;

import java.util.Map;

/**
 * 占位符工具类
 *
 * @author fanbeibei
 * @since 2019-02-22
 */
public class PlaceholderUtil {
    private PlaceholderUtil() {
    }


    /**
     * 将带占位符的字符串格式化。占位符为{}包裹,站位符不可嵌套
     *
     * <pre>
     *
     *  String pattern = "total {fishCount} fish, {deadCount} of which is dead!";
     *  Map<String,String> replaceRuler = new HashMap<>();
     *  replaceRuler.put("fishCount","15");
     *  replaceRuler.put("deadCount","0");
     *  System.out.print(PlaceholderUtil.format(pattern,replaceRuler));
     *
     * 输出结果：total 15 fish, 0 of which is dead!
     * </pre>
     *
     * @param pattern      带占位符字符串
     * @param replaceRuler 替换规则，key为占位符名称,value为替换内容
     * @return
     */
    public static String format(String pattern, Map<String, String> replaceRuler) {
        PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("{", "}");

        return propertyPlaceholderHelper.replacePlaceholders(pattern, new PropertyPlaceholderHelper.PlaceholderResolver() {
            @Override
            public String resolvePlaceholder(String placeholderName) {
                String value = replaceRuler.get(placeholderName);
                return value;
            }
        });
    }


    /**
     * @see {@link #format(String, Map)}
     *
     *
     * @param pattern           带占位符字符串
     * @param replaceRuler      替换规则，key为占位符名称,value为替换内容
     * @param placeholderPrefix 占位符前缀
     * @param placeholderSuffix 占位符后缀
     * @return
     */
    public static String format(String pattern, Map<String, String> replaceRuler, String placeholderPrefix, String placeholderSuffix) {
        PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper(placeholderPrefix, placeholderSuffix);

        return propertyPlaceholderHelper.replacePlaceholders(pattern, new PropertyPlaceholderHelper.PlaceholderResolver() {
            @Override
            public String resolvePlaceholder(String placeholderName) {
                String value = replaceRuler.get(placeholderName);
                return value;
            }
        });
    }


}
